/**
 * 评论的评论
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  TouchableHighlight,
  TouchableOpacity,
  Image,
  Dimensions,
  TextInput,
  KeyboardAvoidingView,
  Button,
  AlertIOS,
} from 'react-native';

import Toast from 'react-native-root-toast';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Config from '../common/config';
import Request from '../common/request';


let width = Dimensions.get('window').width;//获取视口宽度

class Commentcomment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pid: null,
      page: 1,//下一次请求的页码
      pagination: null,
      loading: false,
      refreshing: false,
      data: [],
      textInput: "",
      placeholder: "说说你的看法...",
      textInputHeight: 40,
      comment: null,
    };
  }
  componentDidMount() {
    this.setState({
      comment: this.props.navigation.state.params.comment,
      placeholder: "回复：" + this.props.navigation.state.params.comment.user.data.name
    }, () => {
      this.fetchComments();
    })
    
  }

  fetchComments() {
    var self = this;
    Request.get(Config.api.comment, "tid=" + self.state.comment.tid + "&root_id=" + self.state.comment.id + "&page=" + self.state.page)
    .then((response) => {
      console.log(response);
      self.setState({
        refreshing: false,
        loading: false,
      });
      if (response.ret == 0) {
        if (response.data.pagination.current_page == 1) {
          var newData = response.data.list;
        } else {
          var newData = [...self.state.data, ...response.data.list];
        }
        self.setState({
          data: newData,
          pagination: response.data.pagination,
          page: response.data.pagination.current_page + 1,
        });
      } else {
        Toast.show(response.msg);
      }
      
    })
  }

  renderItemSeparator() {
    return <View style={{width: "100%", height: 1, backgroundColor: "#ddd", marginTop: 20, marginBottom: 20}}/>
  }
  //主评论
  renderHeader() {
    var item = this.props.navigation.state.params.comment;
    return (
      <View style={styles.rootCommentBox}>
        <View style={styles.itemHeader}>
          <Image style={styles.avatar} source={require('../asset/image/avatar.jpg')} />
          <View style={styles.nicknameBox}>
            <Text style={styles.nickname}>{item.user.data.name + " " + item.created_at}</Text>
          </View>
        </View>
        <View style={[styles.itemContent, item.index != 0 ? styles.offsetContent : null]}>
          <Text style={styles.content}>{item.detail.data.content}</Text>
          <View style={styles.images}>
            <Image style={styles.imagesItem} source={require('../asset/image/2.png')} resizeMode='cover' />
            <Image style={styles.imagesItem} source={require('../asset/image/9.png')} resizeMode='cover' />
          </View>
        </View>
      </View>
    );
  }

  onRefresh() {
    if (this.state.loading) {
      return;
    }
    this.setState({
      page: 1,
      refreshing: true,
      loading: true,
    }, () => this.fetchComments())
  }

  onEndReached() {
    if (this.state.page > this.state.pagination.total_pages) {
      return;
    }
    this.fetchComments();
  }

  onItemPress(item) {
    console.log("itemPress...", item);
    this.getTextInput().focus();
    this.setState({
      placeholder: "回复：" + item.user.data.name,
      pid: item.id,
    })
  }

  onTextInputFocus() {
    this.setState({
      textInputHeight: 100,
    })
  }

  onCommentCommentPress(item) {
    console.log("commentCommentPress...", item);
  }

  resetTextInput() {
    let textInput = this.getTextInput();
    textInput.clear();
    textInput.blur();
    this.setState({
      placeholder: "回复：" + this.state.comment.user.data.name,
      pid: null,
      textInputHeight: 40,
      textInput: "",
    })
  }

  onSubmit() {
    var self = this;
    if (!this.state.textInput || !this.state.textInput.trim()) {
      Toast.show("请先输入内容...");
      return;
    }
    if (this.state.loading) {
      return;
    }
    var data = {
      tid: this.state.comment.tid,
      content: this.state.textInput,
    }
    if (self.state.pid) {
      data.pid = self.state.pid
    } else {
      data.pid = self.state.comment.id
    }
    this.setState({
      loading: true,
    })
    Request.post(Config.api.comment, data)
    .then((response) => {
      console.log(response);
      self.setState({
        loading: false,
      })
      if (response.ret == 0) {
        Toast.show("发表成功：" + response.data.comment.id);
        self.resetTextInput();
      } else {
        Toast.show(response.msg);
      }
    })
  }

  getTextInput() {
    return this.refs['textInput'];
  }

  renderItem(item) {
    console.log(item);
    return (
      <TouchableHighlight 
        style={styles.item} 
        onPress={() => this.onItemPress(item)} 
        underlayColor="#ddd"
        activeOpacity={1}
      >
        <View >
          <View style={styles.itemHeader}>
            <Image style={styles.avatar} source={require('../asset/image/avatar.jpg')} />
            <View style={styles.nicknameBox}>
              <Text style={styles.nickname}>{item.user.data.name + " " + item.created_at}</Text>
            </View>
          </View>
          <View style={[styles.itemContent, item.index != 0 ? styles.offsetContent : null]}>
            <Text style={styles.content}>{item.detail.data.content}</Text>
            {/* <View style={styles.images}>
              <Image style={styles.imagesItem} source={require('../asset/image/2.png')} resizeMode='cover' />
              <Image style={styles.imagesItem} source={require('../asset/image/9.png')} resizeMode='cover' />
            </View> */}
          </View>
        </View>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <KeyboardAvoidingView style={styles.container} behavior="padding" keyboardVerticalOffset={60}>
        <FlatList 
          style={styles.list}
          data={this.state.data}
          renderItem={({item, index}) => this.renderItem(item, index)}
          ItemSeparatorComponent={this.renderItemSeparator}
          refreshing={this.state.refreshing}
          onRefresh={() => this.onRefresh()}
          onEndReached={() => this.onEndReached()}
          onEndReachedThreshold={0.2}
          ListHeaderComponent={() => this.renderHeader()}
        />
        <View style={styles.footer}>
          <TextInput 
            ref={"textInput"}
            style={[styles.textInput, {height: this.state.textInputHeight}]}
            onChangeText={(text) => this.setState({textInput: text})}
            placeholder={this.state.placeholder}
            multiline={true}
            underlineColorAndroid="transparent"
            onBlur={() => this.resetTextInput()}
            onFocus={() => this.onTextInputFocus()}
          />
  
          <TouchableHighlight 
            onPress={() => this.onSubmit()} 
            style={styles.btnSubmitBox}
            underlayColor="gray"
          >
            <Text style={styles.btnSubmit}>发送</Text>
          </TouchableHighlight>
          
        </View>
      </KeyboardAvoidingView>
    
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  titleBox: {
    marginBottom: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: "600",
  },
  list: {
    padding: 15,
    backgroundColor: "#ededed"
  },
  item: {
    
  },
  itemHeader: {
    flex: 1,
    flexDirection: 'row',
  },
  nicknameBox: {
    flex: 1,
    justifyContent: 'center',
  },
  nickname: {
    marginBottom: 4
  },
  avatar: {
    width: 32,
    height: 32,
    marginRight: 8,
  },

  content: {
    marginTop: 10,
  },
  images: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: 10,
  },
  imagesItem: {
    flex: 1,
    maxHeight: 200,
  },
  itemFooter: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginTop: 10,
  },
  handleBox: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: 10,
  },
  offsetContent: {
    paddingLeft: 40
  },
  commentCommentArea: {
    backgroundColor: "#ddd",
    marginTop: 10,
    padding: 5
  },
  commentCommentBox: {
    margin: 5,
  },
  commentCommentUser: {
    color: "blue",
  },
  commentCommentContent: {
    color: "#000",
  },
  footer: {
    flexDirection: "row",
    justifyContent: "center",
  },
  textInput: {
    width: "80%",
    padding: 15,
    fontSize: 16,
  },
  btnSubmit: {
    //基本不受样式控制
  },
  btnSubmitBox: {
    width: "20%",
    alignItems: "center",
    backgroundColor: "#ddd",
    justifyContent: "center",
  },
  rootCommentBox: {
    borderBottomWidth: 1,
    borderBottomColor: "#ddd",
    marginBottom: 15,
    paddingBottom: 15,
    backgroundColor: "#fff"
  }




});

module.exports = Commentcomment;

